using System.Linq;
using System.Xml;
using DataScripter.Scripting;
using DataScripter.Scripting.Processes.Morphs;

namespace DataScripter.XmlInterpreter.XmlInterpreters
{
    internal class MorphActionsDefinitionInterpreter : IXmlInterpreter<IMorphActionsDefinition>
    {
        public IEngine Engine { get; set; }

        public MorphActionsDefinitionInterpreter(IEngine engine)
        {
            Engine = engine;
        }

        #region Implementation of IXmlInterpreter<out IMorphActionsDefinition>

        public IMorphActionsDefinition InterpretElement(XmlElement element)
        {
            string name = element.GetAttribute("Name");
            MorphActionsDefinition result = new MorphActionsDefinition(name);
            foreach (XmlElement child in element.ChildNodes.OfType<XmlElement>())
            {
                switch (child.Name)
                {
                    case "Table":
                        InterpretTableMorphs(child, result);
                        break;
                }
            }

            return result;
        }

        private void InterpretTableMorphs(XmlElement xmlElement, MorphActionsDefinition morphActionsDefinition)
        {
            string tableNameFilter = xmlElement.GetAttribute("Name");
            ITableMorphAction tableMorphAction = new TableMorphAction(tableNameFilter);
            foreach (XmlElement child in xmlElement.ChildNodes.OfType<XmlElement>())
            {
                string morphActionName = child.Name;
                IFieldMorphAction morphAction = MorphActionFactory.CreateFieldMorphAction(morphActionName);
                string fields = child.GetAttribute("Fields");
                string fieldName = child.GetAttribute("Name");
                morphAction.FieldFilter = fields;
                morphAction.FieldName = fieldName;
                tableMorphAction.Add(morphAction);
            }
            morphActionsDefinition.AddMorphAction(tableMorphAction);
        }

        #endregion
    }
}